import '@wangeditor/editor/dist/css/style.css' // 引入 css

import React, { useState, useEffect } from 'react'
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor'
import { uploadFile } from "@/request/api"
type InsertFnType = (url: string, alt: string, href: string) => void

function MyEditor(props: any) {
  const { height=300, content, setContent } = props
  // editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null)   // TS 语法

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = { }  // TS 语法
  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {    // TS 语法
    placeholder: '请输入内容...',
    MENU_CONF: {
      uploadImage: {
        async customUpload(file: File, insertFn: InsertFnType) {  // TS 语法
          // file 即选中的文件
          // 自己实现上传，并得到图片 url alt href
          // 最后插入图片
          const formData = new FormData();
          formData.append("file", file)
          uploadFile(formData).then(res => {
            if (res.code === 200) {
              insertFn(res.data, res.data, res.data)
            }
          })
        }
      },
      uploadVideo: {
        async customUpload(file: File, insertFn: InsertFnType) {  // TS 语法
          // file 即选中的文件
          // 自己实现上传，并得到图片 url alt href
          // 最后插入图片
          const formData = new FormData();
          formData.append("file", file)
          uploadFile(formData).then(res => {
            if (res.code === 200) {
              insertFn(res.data, res.data, res.data)
            }
          })
        }
      },
    },
  }

  const onChange = (edit: IDomEditor) => {
    setContent(edit.getHtml())
  }

  // 及时销毁 editor ，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])

  return (
      <>
          <div style={{ border: '1px solid #ccc', zIndex: 100}}>
              <Toolbar
                  editor={editor}
                  defaultConfig={toolbarConfig}
                  mode="default"
                  style={{ borderBottom: '1px solid #ccc' }}
              />
              <Editor
                  defaultConfig={editorConfig}
                  value={content}
                  onCreated={setEditor}
                  onChange={onChange}
                  mode="default"
                  style={{ height: height + 'px', overflowY: 'hidden' }}
              />
          </div>
      </>
  )
}

export default MyEditor